<route lang="json5">
	{
	needLogin: false,
	style: {
	navigationStyle: 'default',
	navigationBarTitleText: '',
	navigationBarBackgroundColor: '#ffffff',
	},
	}
</route>
<template>
	<view class="min-h-screen bg-white">
		<!-- 顶部导航栏 -->
		<!--  <wd-navbar 
      left-arrow
      placeholder
      @click-left="handleBack"
      custom-style="background: #fff; border-bottom: none;"
      fixed
      safeAreaInsetTop
    ></wd-navbar> -->

		<!-- 修改密码表单 -->
		<view class="px-[32rpx] pt-[48rpx]">
			<!-- 标题区域 -->
			<view class="mb-[72rpx] text-center">
				<view class="text-[40rpx] font-bold color-#333333 mb-[16rpx]">忘记密码</view>
				<view class="text-[28rpx] color-#999999">请填写验证码后输入新密码</view>
			</view>

			<!-- 表单区域 -->
			<view>
				<!-- 手机号输入 -->
				<view class="flex flex-col mb-[32rpx]">
					<view class="flex items-center justify-start h-[86rpx] pl-[12rpx] bg-#F6F9FE border-rd-60rpx">
						<!-- <image
              src="/static/images/login/username.png"
              class="w-[36rpx] h-[36rpx]"
              mode="aspectFit"
            /> -->
						<wd-input v-model="form.phone" clear-trigger="focus" clearable placeholder="请输入手机号" no-border
							class="flex-1" :custom-class="inputClass" :maxlength="11" type="number"
							@blur="handlePhoneBlur" />
					</view>
					<text v-if="showPhoneError" class="text-[22rpx] color-#ff3b30 mt-[8rpx] ml-[12rpx]">
						请输入正确的手机号
					</text>
				</view>

				<!-- 验证码输入 -->
				<view class="flex flex-col mb-[32rpx]">
					<view class="flex items-center justify-start h-[86rpx] pl-[12rpx] bg-#F6F9FE border-rd-60rpx">
						<!-- <image
              src="/static/images/login/pass.png"
              class="w-[36rpx] h-[36rpx]"
              mode="aspectFit"
            /> -->
						<wd-input v-model="form.code" clear-trigger="focus" clearable placeholder="请输入验证码" no-border
							class="flex-1" :custom-class="inputClass" :maxlength="6" type="number" />
						<view class="verify-code-btn mr-[12rpx] w-[180rpx] h-[60rpx] flex items-center justify-center"
							:class="{ disabled: !canSendCode || counting }" @click="handleSendCode">
							{{ counting ? `${countdown}秒后重发` : '获取验证码' }}
						</view>
					</view>
					<text v-if="showCodeError" class="text-[22rpx] color-#ff3b30 mt-[8rpx] ml-[12rpx]">
						请输入6位验证码
					</text>
				</view>

				<!-- 新密码输入 -->
				<view class="flex flex-col mb-[72rpx]">
					<view class="flex items-center justify-start h-[86rpx] pl-[12rpx] bg-#F6F9FE border-rd-60rpx">
						<!-- <image
              src="/static/images/login/pass.png"
              class="w-[36rpx] h-[36rpx]"
              mode="aspectFit"
            /> -->
						<wd-input v-model="form.password" clear-trigger="focus" clearable show-password
							placeholder="新密码（6-18位字母数字组合）" no-border class="flex-1" :custom-class="inputClass"
							:maxlength="18" @input="handlePasswordInput" type="text" />
					</view>
					<text v-if="showPasswordError" class="text-[22rpx] color-#ff3b30 mt-[8rpx] ml-[12rpx]">
						密码必须为6-18位字母数字组合
					</text>
				</view>

				<!-- 确定按钮 -->
				<wd-button size="large" type="primary" block :disabled="!isFormValid" @click="handleSubmit"
					custom-class="submit-button" class="h-[88rpx] rounded-full bg-gradient-linear">
					确定
				</wd-button>
			</view>
		</view>

		<!-- 修改结果页面 -->
		<uni-popup ref="popup" type="center">
			<template #default>
				<view
					style="background-color: white; border-radius: 20rpx; padding-left: 80rpx; padding-right: 80rpx; padding-bottom: 40rpx;">

					<!-- 图片区域 -->
					<view class="flex justify-center mb-[20rpx]">
						<image :src="isSuccess ? '/static/images/login/success.png' : '/static/images/login/fail.png'"
							class="w-[320rpx] h-[320rpx]" mode="aspectFit" />
					</view>

					<!-- 标题区域 -->
					<view class="mb-[45rpx] text-center">
						<view class="text-[40rpx] font-bold color-#333333 mb-[16rpx]">
							{{ isSuccess ? '修改成功' : '修改失败' }}
						</view>
						<view class="text-[28rpx] color-#999999">
							{{ dialogTips }}
						</view>
					</view>

					<!-- 按钮 -->
					<wd-button size="large" type="primary" block class="h-[88rpx] w-[400rpx] rounded-full"
						@click="handleResultButtonClick">
						{{ isSuccess ? '去登录' : '我知道了' }}
					</wd-button>

				</view>

			</template>

		</uni-popup>

	</view>
</template>

<script setup lang="ts">
	import { updatePasApi } from '@/service/auth'
	import { changePassword, sendSmsCode, verifySmsCode } from '@/service/edu/teachers'
	import { ref, computed, watch } from 'vue'
	import config from '@/utils/config'

	const inputClass = 'bg-gray-100 rounded-lg !border-0'

	// 获取 uni-popup 的引用
	const popup = ref(null);

	// 表单数据
	const form = ref({
		phone: '',
		code: '',
		password: '',
		tenantId: '',
	})

	// 倒计时相关
	const counting = ref(false)
	const countdown = ref(60)
	let timer : any = null
	const dialogTips : any = ref("")

	// 手机号验证
	const isPhoneValid = computed(() => {
		return /^1[3-9]\d{9}$/.test(form.value.phone)
	})

	// 是否可以发送验证码
	const canSendCode = computed(() => {
		return isPhoneValid.value && !counting.value
	})

	// 表单是否有效
	const isFormValid = computed(() => {
		return (
			isPhoneValid.value &&
			form.value.code.length === 6 &&
			/^[a-zA-Z0-9]{6,18}$/.test(form.value.password)
		)
	})

	// 错误提示控制
	const showPhoneError = ref(false)
	const showCodeError = ref(false)
	const showPasswordError = ref(false)

	// 处理手机号输入
	const handlePhoneInput = (value : any) => {
		const strValue = String(value || '')
		form.value.phone = strValue.replace(/[^\d]/g, '')
	}

	// 处理手机号失焦
	const handlePhoneBlur = () => {
		showPhoneError.value = form.value.phone.length > 0 && !isPhoneValid.value
	}

	// 处理密码输入
	const handlePasswordInput = (value : any) => {
		if (typeof value === 'object') {
			return
		}
		const strValue = String(value || '')
		form.value.password = strValue.replace(/[^a-zA-Z0-9]/g, '')
		showPasswordError.value =
			form.value.password.length > 0 && !/^[a-zA-Z0-9]{6,18}$/.test(form.value.password)
	}

	// 监听验证码输入
	watch(
		() => form.value.code,
		(newVal) => {
			showCodeError.value = newVal.length > 0 && newVal.length !== 6
		},
	)

	// 发送验证码
	const handleSendCode = async () => {
		if (!canSendCode.value) return

		// 先校验手机号
		if (!isPhoneValid.value) {
			showPhoneError.value = true
			uni.showToast({
				title: '请输入正确的手机号',
				icon: 'none',
			})
			return
		}

		try {
			// TODO: 调用发送验证码接口
			await sendSmsCode({
				phoneNumber: form.value.phone,
			})

			uni.showToast({
				title: '验证码已发送',
				icon: 'success',
			})

			// 开始倒计时
			counting.value = true
			countdown.value = 60
			timer = setInterval(() => {
				if (countdown.value <= 1) {
					clearInterval(timer)
					counting.value = false
					countdown.value = 60
				} else {
					countdown.value--
				}
			}, 1000)
		} catch (error) {
			console.error('发送验证码失败:', error)
			uni.showToast({
				title: '发送验证码失败',
				icon: 'error',
			})
		}
	}

	// 结果页面控制
	const showResult = ref(false)
	const isSuccess = ref(false)

	// 提交表单
	const handleSubmit = async () => {
		// 显示所有错误提示
		showPhoneError.value = !isPhoneValid.value
		showCodeError.value = form.value.code.length !== 6
		showPasswordError.value = !/^[a-zA-Z0-9]{6,18}$/.test(form.value.password)

		if (!isFormValid.value) return

		try {
			console.log('form.value======', form.value)
			const verifyData = await verifySmsCode({
				phoneNumber: form.value.phone,
				smsCode: form.value.code,
			})
			if (verifyData && verifyData.code === 200) {
				// TODO: 调用重置密码接口
				const res = await changePassword({
					phoneNumber: form.value.phone,
					newPassword: form.value.password,
					smsCode: form.value.code,
					tenantId: config.tenantId,
				})
				if (res && res.code == 200) {
					// uni.showToast({
					// 	title: res.msg,
					// 	icon: 'error',
					// })
					// return
					dialogTips.value = "您的密码已修改"
					// 接口调用成功
					isSuccess.value = true
					showResult.value = true
				} else {
					dialogTips.value = res.msg
					// 接口调用失败
					isSuccess.value = false
					showResult.value = true
				}
			} else {
				// uni.showToast({
				// 	title: verifyData.msg,
				// 	icon: 'error',
				// })
				dialogTips.value = verifyData.msg
			}

		} catch (error) {
			console.error('重置密码失败:', error)
			isSuccess.value = false
			showResult.value = true
			dialogTips.value = "网络走丢了，请重新试一下"
		} finally {
			popup.value.open('center');
		}
	}

	// 结果页面按钮点击
	const handleResultButtonClick = () => {
		if (isSuccess.value) {
			// 成功时跳转到登录页
			uni.reLaunch({
				url: '/pages/login/index',
			})
		} else {
			// 失败时返回修改页面
			showResult.value = false
			popup.value.close('center');
		}
	}

	// 返回按钮处理
	const handleBack = () => {
		if (showResult.value) {
			if (isSuccess.value) {
				uni.reLaunch({
					url: '/pages/login/index',
				})
			} else {
				showResult.value = false
			}
		} else {
			const pages = getCurrentPages()
			if (pages.length > 1) {
				uni.navigateBack()
			} else {
				uni.reLaunch({
					url: '/pages/login/index',
				})
			}
		}
	}

	// 组件销毁时清除定时器
	onUnmounted(() => {
		if (timer) {
			clearInterval(timer)
		}
	})
</script>

<style lang="scss" scoped>
	:deep(.wd-input) {
		flex: 1;
		margin-right: 20rpx;
		margin-left: 20rpx;
		background-color: #f6f9fe;
		border-radius: 8rpx;
	}

	:deep() {
		.wd-message-box {
			.custom-shadow {
				box-shadow: 0 3px 1px -2px rgb(0 0 0 / 20%), 0 2px 2px 0 rgb(0 0 0 / 14%), 0 1px 5px 0 rgb(0 0 0 / 12%);
			}
		}
	}

	.verify-code-btn {
		font-size: 22rpx;
		color: #3670f7;
		cursor: pointer;
		user-select: none; // 防止文字被选中
		background: transparent;
		border-left: 2rpx olid #e8e8e8;

		&.disabled {
			color: #999999;
			cursor: not-allowed;
		}

		&:active:not(.disabled) {
			opacity: 0.8; // 点击效果
		}
	}

	:deep(.wd-button--primary) {
		background: linear-gradient(to right, #7bffe6, #19d18b);
		border: none;

		&.is-disabled {
			background: #b3f0d9;
			opacity: 1;
		}
	}

	:deep(.wd-navbar__title) {
		font-size: 34rpx;
		font-weight: 500;
		color: #333;
	}

	:deep(.wd-input__inner) {
		padding: 0 24rpx;
		font-size: 28rpx;
		color: #333333;
	}

	.submit-button {
		background: linear-gradient(90deg, #1FA1FF 2%, #0C55FE 40%) !important;
		border-radius: 50px 50px 50px 50px !important;
	}

	:deep(.uni-checkbox-input) {
		width: 34rpx;
		height: 34rpx;
		border: 1rpx solid #3670f7;
		border-radius: 4rpx;
		transform: scale(0.7);
	}

	:deep(.wd-input__icon) {
		background: #f7f7f7 !important;
	}
</style>